package com.mti.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mti.constant.AlarmFilterEnum;
import com.mti.dao.dto.OrganizationDto;
import com.mti.dao.model.KmJurisdictionEntity;
import com.mti.dao.model.KmRlsbEntity;
import com.mti.dao.model.LfZdryBaseEntity;
import com.mti.dao.model.LfZtryyjEntity;
import com.mti.service.*;
import com.mti.utils.AddressOrLngLatConvertUtil;
import com.mti.utils.ZdryYjUtilBean;
import com.mti.websocket.SocketType;
import com.mti.websocket.WebSocketUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 人脸识别 前端控制器
 * </p>
 *
 * @author duchao
 * @since 2020-06-19
 */
@Api("人脸识别")
@RestController
@RequestMapping("/kmRlsb")
@Slf4j
public class KmRlsbController {

    @Autowired
    private KmRlsbService kmRlsbService;
    @Autowired
    private AddressOrLngLatConvertUtil addressOrLngLatConvertUtil;
    @Autowired
    private KmJurisdictionService kmJurisdictionService;
    @Autowired
    private ILfZtryyjsjService iLfZtryyjsjService;
    @Autowired
    private WebSocketUtils webSocketUtils;
    @Autowired
    private CacheableService cacheableService;
    @Autowired
    private LfZdryBaseService lfZdryBaseService;
    @Autowired
    private KmAlarmAreaService kmAlarmAreaService;
    @Autowired
    private KmAlarmTypeService kmAlarmTypeService;

    @ApiOperation("人脸预警接受")
    @PostMapping("/VIID/DispositionNotifications")
    public Object receiveRlsbYj(@RequestBody KmRlsbEntity kmRlsbEntity) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //主键判断
            Integer count = kmRlsbService.count(new QueryWrapper<KmRlsbEntity>().lambda().eq(KmRlsbEntity::getNotificationID, kmRlsbEntity.getNotificationID()));
            if (count > 0) {
                resultMap.put("Id", kmRlsbEntity.getNotificationID());
                resultMap.put("StatusCode", -1);
                resultMap.put("StatusString", "预警主键已经存在");
                return resultMap;
            }
            //一小时内 身份证号 和 设备名称相同 不入库
            boolean existFlag = kmRlsbService.findRlsbInfo(kmRlsbEntity);
            if (existFlag) {
                resultMap.put("Id", kmRlsbEntity.getNotificationID());
                resultMap.put("StatusCode", -1);
                resultMap.put("StatusString", "预警消息已经存在");
                return resultMap;
            }
            boolean insertFlag = kmRlsbService.save(kmRlsbEntity);

            if (insertFlag) {

                LfZtryyjEntity lfZtryyjEntity = kmRlsbEntity.convertZdryYj();
                // 设置默认坐标
                if ("".equals(kmRlsbEntity.getDeviceName()) || null == kmRlsbEntity.getDeviceName()) {
                    if ("".equals(kmRlsbEntity.getLongitude()) || null == kmRlsbEntity.getLongitude() && "".equals(kmRlsbEntity.getLatitude()) || null == kmRlsbEntity.getLatitude()) {
                        return resultMap;
                    }
                } else {
                    if ("".equals(kmRlsbEntity.getLongitude()) || null == kmRlsbEntity.getLongitude() && "".equals(kmRlsbEntity.getLatitude()) || null == kmRlsbEntity.getLatitude()) {
                        kmRlsbEntity.setLongitude("102.719775");
                        kmRlsbEntity.setLatitude("24.839721");
                    }
                }

                String currentJur = addressOrLngLatConvertUtil.checkAddress(kmRlsbEntity.getLongitude(), kmRlsbEntity.getLatitude());
                lfZtryyjEntity.setCurrentJur(currentJur);

                // 先通过推送过来的派出所编码（有可能是分局的编码）去匹配派出所或者分局
                String jurisdictionUnit = null;
                if (null != kmRlsbEntity.getDepartment() && kmRlsbEntity.getDepartment().length() > 0) {
                    List<OrganizationDto> orgs = cacheableService.getUpOrgById(kmRlsbEntity.getDepartment());
                    if (orgs.size() > 0) {
                        OrganizationDto org = orgs.get(orgs.size() - 1);
                        if (org.getShortName().indexOf("派出所") >= 0) { //传过来的为派出所编码
                            jurisdictionUnit = org.getShortName();
                            lfZtryyjEntity.setYjdPcs(org.getShortName());
                            lfZtryyjEntity.setYjdPcsCode(org.getId());
                            if (orgs.size() > 2) lfZtryyjEntity.setYjdSsfj(orgs.get(orgs.size() - 2).getShortName());
                        } else { // 传过来的为分局编码
                            jurisdictionUnit = orgs.get(orgs.size() - 1).getShortName();
                            lfZtryyjEntity.setYjdSsfj(orgs.get(orgs.size() - 1).getShortName());
                        }
                    }
                } else {
                    // 如果没有匹配不到 再用坐标到辖区表中匹配
                    KmJurisdictionEntity kmJurisdictionEntity = kmJurisdictionService.queryYjdPcsByLngAndLat(kmRlsbEntity.getLongitude(), kmRlsbEntity.getLatitude());
                    if (null != kmJurisdictionEntity) {
                        jurisdictionUnit = kmJurisdictionEntity.getMc();
                        lfZtryyjEntity.setYjdPcs(kmJurisdictionEntity.getMc());
                        lfZtryyjEntity.setYjdPcsCode(String.format("%.0f", Double.parseDouble(kmJurisdictionEntity.getDm())));
                        lfZtryyjEntity.setYjdSsfj(kmJurisdictionEntity.getSsfj());
                    }
                }
                boolean ylSign = iLfZtryyjsjService.save(lfZtryyjEntity);
                ZdryYjUtilBean zdryYjUtilBean = lfZtryyjEntity.convertZdryYjUtilBean();

                if (null != jurisdictionUnit) {
                    StringBuilder sb = new StringBuilder("重点人员【");
                    sb.append(lfZtryyjEntity.getRyxm()).append("】在").append(jurisdictionUnit).append("的管辖范围内发生了人脸识别预警。");
                    zdryYjUtilBean.setYjMsg(sb.toString());
                }

                if (ylSign) {
                    //检测是否符合预警推送规则
                    boolean isAllowed = iLfZtryyjsjService.authEarlyWarning(lfZtryyjEntity, AlarmFilterEnum.RLSB_SWITCH.getName());
                    if (!isAllowed) {
                        return resultMap;
                    }

                    //查询此条预警是否是灰名单 或者是 已稳控  如果是就不推送
                    LfZdryBaseEntity entity = lfZdryBaseService.getOne(new QueryWrapper<LfZdryBaseEntity>().eq("sfzh", lfZtryyjEntity.getYjbs()).ne("gkjb", "灰名单").ne("wkzt", "已稳控"));
                    if (!ObjectUtils.isEmpty(entity)) {
                        return resultMap;
                    }
                    List<String> tokens = iLfZtryyjsjService.findWebsocketPsuhUserListByYjwybs(lfZtryyjEntity.getWybs());
                    if (null != tokens && tokens.size() > 0) {
                        webSocketUtils.sendWebsockMessageToUser(tokens, Arrays.asList("rlsb", JSON.toJSONString(zdryYjUtilBean)), SocketType.ZDRRYJXX.getCode());
                    }

                }
                resultMap.put("StatusCode", 0);
                resultMap.put("StatusString", "ok");
            }
            return resultMap;
        } catch (NumberFormatException e) {
            resultMap.put("Id", kmRlsbEntity.getNotificationID());
            resultMap.put("StatusCode", -1);
            resultMap.put("StatusString", "接口调用发生异常！");
            return resultMap;
        }
    }

}

